import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'dart:io';

import '../../common/index.dart';

class SettingPage extends ConsumerStatefulWidget {
  const SettingPage({super.key});

  @override
  ConsumerState<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends ConsumerState<SettingPage> {
  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text(
          'Settings',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20.sp,
            fontFamily: 'Port',
            fontWeight: FontWeight.w400,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios_new_rounded, color: Colors.white),
          onPressed: () {
            if (Navigator.canPop(context)) {
              context.goBack();
            } else {
              context.navigateTo(AppRoutes.main);
            }
          },
        ),
      ),
      body: SafeArea(
        bottom: false,
        top: false,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(MyImages.homeBg),
              fit: BoxFit.fill,
            ),
          ),
          child: Stack(
            children: [
              // 用户头像
              Positioned(
                top: 125.h,
                left: 0,
                right: 0,
                child: Container(
                  width: 111.01.w,
                  height: 110.w,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(65.r),
                    ),
                  ),
                  child: GestureDetector(
                    onTap: _handleAvatarTap,
                    child: Stack(
                      children: [
                        Positioned(
                          left: 132.w,
                          child: Container(
                            width: 111.01.w,
                            height: 110.w,
                            decoration: ShapeDecoration(
                              color: const Color(0xFFFF8F05),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(65.r),
                              ),
                            ),
                          ),
                        ),
                        Positioned(
                          left: 132.w,
                          child: Container(
                            width: 111.01.w,
                            height: 110.w,
                            decoration: ShapeDecoration(
                              image: DecorationImage(
                                image: _getAvatarImageProvider(
                                  currentUser?.avatar,
                                ),
                                fit: BoxFit.cover,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(65.r),
                              ),
                            ),
                          ),
                        ),
                        Positioned(
                          right: 142.w,
                          bottom: 0.h,
                          child: Container(
                            width: 24.w,
                            height: 24.h,
                            decoration: ShapeDecoration(
                              color: const Color(0xFFFF8F05),
                              shape: OvalBorder(
                                side: BorderSide(width: 1, color: Colors.white),
                              ),
                            ),
                            child: Icon(
                              Icons.camera_alt,
                              color: Colors.white,
                              size: 12.sp,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

              // 用户名和隐私政策等
              Positioned(
                top: 325.h,
                left: 0,
                right: 0,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    spacing: 24.w,
                    children: [
                      SizedBox(
                        width: 343.w,
                        child: Row(
                          spacing: 12.w,
                          children: [
                            Text(
                              'name',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 14.sp,
                                fontFamily: 'PingFang SC',
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                            Expanded(
                              child: GestureDetector(
                                onTap: _handleUsernameEdit,
                                child: Container(
                                  height: 44.h,
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 12.w,
                                  ),
                                  decoration: ShapeDecoration(
                                    color: Colors.white.withValues(alpha: 0.50),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(14.r),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          currentUser?.username ?? 'Guest',
                                          style: TextStyle(
                                            color: Colors.black87,
                                            fontSize: 14.sp,
                                            fontFamily: 'PingFang SC',
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                      Icon(
                                        Icons.edit,
                                        color: Colors.grey[600],
                                        size: 16.sp,
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      _buildItem(
                        text: 'Privacy Policy',
                        onTap: () {
                          UrlUtils().openUrl(UrlUtils.PRIVACY_POLICY);
                        },
                      ),
                      _buildItem(
                        text: 'Terms Of service',
                        onTap: () {
                          UrlUtils().openUrl(UrlUtils.TERMS_OF_SERVICE);
                        },
                      ),
                      _buildItem(
                        text: 'Delete Account',
                        onTap: _handleDeleteAccount,
                      ),
                    ],
                  ),
                ),
              ),

              // 退出登录
              Positioned(
                bottom: 150.h,
                left: 16.w,
                right: 16.w,
                child: GestureDetector(
                  onTap: () async {
                    await ref.read(userProvider.notifier).logout();
                    if (mounted) {
                      if (context.mounted) {
                        context.navigateTo(AppRoutes.main);
                      }
                    }
                  },
                  child: Container(
                    width: 351.w,
                    height: 58.h,
                    decoration: ShapeDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.00, 0.50),
                        end: Alignment(1.00, 0.50),
                        colors: [
                          const Color(0xFFFF8C00),
                          const Color(0xFFF8FFC7),
                        ],
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(67.r),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        'Log out',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 16.sp,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildItem({required String text, required VoidCallback onTap}) {
    return InkWell(
      onTap: onTap,
      child: Row(
        children: [
          SizedBox(
            child: Text(
              text,
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
          Spacer(),
          SizedBox(
            width: 24.w,
            height: 24.h,
            child: Icon(Icons.arrow_forward_ios, color: Colors.white),
          ),
        ],
      ),
    );
  }

  /// 获取头像图片提供者
  ImageProvider _getAvatarImageProvider(String? avatarPath) {
    if (avatarPath == null || avatarPath.isEmpty) {
      return AssetImage(MyImages.settingAvatar);
    }

    if (avatarPath.startsWith('assets/')) {
      return AssetImage(avatarPath);
    } else {
      // 本地文件路径
      final file = File(avatarPath);
      if (file.existsSync()) {
        return FileImage(file);
      } else {
        return AssetImage(MyImages.settingAvatar);
      }
    }
  }

  /// 处理头像点击
  void _handleAvatarTap() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      _showMessage('User not found', isError: true);
      return;
    }

    try {
      // 直接从相册选择图片，避免复杂的底部弹窗
      final imagePath = await ImagePickerUtil.pickImageFromGallery();

      if (imagePath != null && mounted) {
        setState(() {});

        // 更新用户头像
        final updatedUser = currentUser.copyWith(avatar: imagePath);
        final success = await ref
            .read(userProvider.notifier)
            .updateUser(updatedUser);

        if (success && mounted) {
          _showMessage('Avatar updated successfully');
        } else if (mounted) {
          _showMessage('Failed to update avatar', isError: true);
        }
      }
    } catch (e) {
      debugPrint('Avatar selection error: $e');
      if (mounted) {
        String errorMessage = 'Failed to select image';
        if (e.toString().contains('channel-error')) {
          errorMessage =
              'Camera/Gallery access error. Please check permissions.';
        } else if (e.toString().contains('permission')) {
          errorMessage =
              'Permission denied. Please allow camera/gallery access.';
        }
        _showMessage(errorMessage, isError: true);
      }
    } finally {
      if (mounted) {
        setState(() {});
      }
    }
  }

  /// 处理用户名编辑
  void _handleUsernameEdit() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) return;

    await showUsernameEditDialog(
      context: context,
      currentUsername: currentUser.username,
      onConfirm: (newUsername) async {
        // 检查用户名是否已存在
        if (UserService.isUsernameExists(newUsername) &&
            newUsername != currentUser.username) {
          throw Exception('username already exists');
        }

        // 更新用户名
        final updatedUser = currentUser.copyWith(username: newUsername);
        final success = await ref
            .read(userProvider.notifier)
            .updateUser(updatedUser);

        if (!success) {
          throw Exception('update failed');
        }

        if (mounted) {
          _showMessage('Username updated successfully');
        }
      },
    );
  }

  /// 处理删除账号
  void _handleDeleteAccount() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      _showMessage('User not found', isError: true);
      return;
    }

    await showDeleteAccountDialog(
      context: context,
      onConfirm: () async {
        try {
          final success = await ref.read(userProvider.notifier).deleteAccount();

          if (success && mounted) {
            _showMessage('Account deleted successfully');
            // 延迟一下再跳转，让用户看到成功消息
            await Future.delayed(Duration(milliseconds: 1500));
            if (mounted && context.mounted) {
              context.navigateTo(AppRoutes.main);
            }
          } else if (mounted) {
            _showMessage('Failed to delete account', isError: true);
          }
        } catch (e) {
          if (mounted) {
            _showMessage('Delete account failed: $e', isError: true);
          }
        }
      },
    );
  }

  /// 显示消息提示
  void _showMessage(String message, {bool isError = false}) {
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : Colors.green,
        duration: Duration(seconds: 3),
      ),
    );
  }
}
